package io.serializable;

import framework.AbstractTest;
import utils.Log;

import java.io.*;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created by shane on 2018/5/28.
 */
public class SerialCtl extends AbstractTest implements Serializable {

    private static final String TAG = "SerialCtl";
    private static final long serialVersionUID = 7798038101149966582L;

    private String a;
    private transient String b;

    public SerialCtl() {
    }

    public SerialCtl(String aa, String bb) {

        this.a = aa;
        this.b = bb;
    }

    @Override
    public String toString() {
        return a + "\n" + b;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.defaultWriteObject();

        out.writeObject(b);
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        b = (String) in.readObject();
    }

    @Override
    public void test(String[] args) {
        super.test(args);
        String outPath = getDefTempFile(args);

        try {
            SerialCtl a = new SerialCtl("Test1 ", " Test2");
            Log.vn("before : " + a);

            ByteArrayOutputStream buf = new ByteArrayOutputStream();

            ObjectOutputStream o = new ObjectOutputStream(buf);
            Log.vn("saving objects:");
            o.writeObject(a);
            o.close();

            TimeUnit.SECONDS.sleep(1);

            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf.toByteArray()));
            Log.vn("recovering objects at:" + new Date());
            a = (SerialCtl) in.readObject();
            Log.vn("logon a = " + a);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String getTag() {
        return TAG;
    }
}
